let express = require("express")
let app = express()
let db = require("./db")
let cityModel = require("./model/cityModel")

db.then(() => {
    // 获取中国所有省份信息
    app.get("/get_all_province", (req, resp) => {
        try {
            cityModel.find({level: 1}, {name: 1, province: 1, _id: 0}, (err, data) => {
                let result = {}
                if(!err){
                    result = {state: 1, data: data, msg: "ok"}
                }else{
                    console.log("获取数据失败")
                    result = {state: 0, data: {}, msg: "获取数据失败"}
                }
                resp.json(result)
            })
        } catch (err) {
            console.log(err)
            resp.send("网络不稳定, 稍后重试")
        }
    })  

    // 根据省份信息获取该省下所有市信息
    app.get("/get_city_byProCode", (req, resp) => {
        try {
            const {province} = req.query 
            cityModel.find({level: 2, province}, {name: 1, city: 1, _id: 0},(err, data) => {
                let result = {}
                if(!err){
                    result = {state: 1, data: data, msg: "ok"}
                }else{
                    console.log("获取数据失败")
                    result = {state: 0, data: {}, msg: "获取数据失败"}
                }
                resp.json(result)
            })
        } catch (err) {
            console.log(err)
            resp.send("网络不稳定, 稍后重试")
        }
    })  

    // 根据省信息和市信息获取该市下区县信息
    app.get("/get_county_byProCodeAndCityCode", (req, resp) => {
        try {
            const {province, city} = req.query 
            cityModel.find({level: 3, province, city}, {name: 1, code: 1, _id: 0},(err, data) => {
                let result = {}
                if(!err){
                    result = {state: 1, data: data, msg: "ok"}
                }else{
                    console.log("获取数据失败")
                    result = {state: 0, data: {}, msg: "获取数据失败"}
                }
                resp.json(result)
            })
        } catch (err) {
            console.log(err)
            resp.send("网络不稳定, 稍后重试")
        }
    })  
}).catch((err) => {
    console.log(err)
})

app.listen(3000, (err) => {
    if(!err){
        console.log("三级联动服务器启动成功")
    }else{
        console.log(err)
    }
})